package cn.elwy.rcp.ui.explorer.core.handler;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.apache.maven.shared.invoker.InvocationResult;

import cn.elwy.common.exception.RunException;
import cn.elwy.common.util.AssertUtil;
import cn.elwy.common.util.PathUtil;
import cn.elwy.common.util.io.FileUtil;
import cn.elwy.common.util.io.ListFileFilter;
import cn.elwy.osgi.config.ConfigContext;
import cn.elwy.rcp.core.model.ui.progress.ProgressMonitor;
import cn.elwy.rcp.ui.explorer.core.JarNameUtil;
import cn.elwy.rcp.ui.explorer.core.PathConst;

import cn.elwy.rcp.ui.explorer.core.ProjectConst;
import cn.elwy.rcp.ui.explorer.core.util.MavenUtil;
import cn.elwy.rcp.ui.explorer.core.vo.BuilderModule;
import cn.elwy.rcp.ui.explorer.core.vo.ProjectConfig;

public class MavenHandler extends ProjectServiceHandler {

	private ListFileFilter listFileFilter;
	private ListFileFilter listFileFilter1;
	private FileFilter filter = new FileFilter() {

		@Override
		public boolean accept(File f) {
			return f.isDirectory() && !f.getName().equalsIgnoreCase(".svn");
		}
	};

	public MavenHandler() {
		listFileFilter = new ListFileFilter("^*.jar", true, false);
		listFileFilter1 = new ListFileFilter("^*.jar", true, false);
	}

	@Override
	public Object handler(ProjectConfig pc, ProgressMonitor monitor) {
		File mavenHome = ConfigContext.getMavenHome();
		String[] cmd = pc.getMvnCmd().split(" ");// PathConst.BUILDER_COMMAND;
		List<BuilderModule> moduleList = pc.getModuleList();
		boolean state = true;
		int i = 1;
		String destPath = PathUtil.getFilePath(pc.getOutputDir(), PathConst.OUTPUT_EXE_UPDATE_DIR);

		monitor.beginTask("构建代码", moduleList.size());
		try {
			for (BuilderModule keyValue : moduleList) {
				if (!keyValue.isBuilder()) {
					continue;
				}
				if (monitor.isCanceled()) {
					isContinue = false;
					return false;
				}
				File pomFile = new File(keyValue.getFilePath());
				monitor.subTask(pomFile.toString());
				String outDirectory = keyValue.getOutDirectory();
				try {
					executePom(monitor, mavenHome, cmd, destPath, pomFile, outDirectory);
				} catch (Exception e) {
					if (pc.isErrorBreak()) {
						throw e;
					}
				}
				monitor.worked(i++);
			}
			// 获取容器路径，获取输出路径，

			if (pc.getPackType() == ProjectConst.PACK_TYPE_WAR) {
				String containerDirectory = pc.getContainerDirectory();
				if (AssertUtil.isNotEmpty(containerDirectory)) {
					String filePath = PathUtil.getFilePath(pc.getResourcePath(), containerDirectory);
					if (!containerDirectory.startsWith("/")) {
						filePath = containerDirectory;
					}
					File pomFile = new File(filePath, "pom.xml");
					if (!pomFile.exists()) {
						throw new RunException(pomFile + "文件不存在！");
					}
					destPath = PathUtil.getFilePath(pc.getOutputDir(), PathConst.OUTPUT_EXE_DIR);
					monitor.subTask(pomFile.toString());
					executePom(monitor, mavenHome, cmd, destPath, pomFile, "");
					monitor.worked(i++);
				}
			}
		} catch (Throwable e) {
			throw new RunException(e.getMessage(), e);
		} finally {
		}
		monitor.worked(i);
		return state;
	}

	private InvocationResult executePom(ProgressMonitor monitor, File mavenHome, String[] cmd, String destPath,
			File pomFile, String outDirectory) throws IOException {
		InvocationResult result = MavenUtil.execute(pomFile, mavenHome, Arrays.asList(cmd));
		if (result.getExitCode() == 99) {
			String message = null;
			if (result.getExecutionException() != null) {
				message = pomFile.getAbsolutePath() + "：打包失败！错误：" + result.getExecutionException().getMessage();
				monitor.subTask(message);
			} else {
				message = pomFile.getAbsolutePath() + "：打包失败！错误码：" + result.getExitCode();
				monitor.subTask(message);
			}
			throw new RunException(message);
		} else {
			String destDir = PathUtil.getFilePath(destPath, outDirectory);
			// 打包成功，复制jar包到目录
			File parentFile = pomFile.getParentFile();
			File targetFile = new File(parentFile, PathConst.TARGET);
			if (targetFile.exists()) {
				File[] listFiles = targetFile.listFiles(listFileFilter);
				if (listFiles != null) {
					for (File file : listFiles) {
						String de = PathUtil.getFilePath(destDir, file.getName());
						FileUtil.copyFiles(file.getAbsolutePath(), de, true, null);
					}
					return result;
				}
			}
			copy(parentFile, destDir);
		}
		return result;
	}

	private void copy(File parentFile, String destDir) throws IOException {
		File[] listFiles = parentFile.listFiles(filter);
		if (listFiles != null) {
			target: for (File file : listFiles) {
				File targetFile1 = new File(file, PathConst.TARGET);
				if (targetFile1.exists()) {
					File[] listFiles1 = targetFile1.listFiles(listFileFilter1);
					String[] ignoreCopyJar = PathConst.IGNORE_COPY_JAR;
					if (listFiles1 != null) {
						for (File file1 : listFiles1) {
							String name = file1.getName();
							String de = PathUtil.getFilePath(destDir, name);
							String jarName = JarNameUtil.getName(name);
							for (String ignoreJar : ignoreCopyJar) {
								if (jarName.contains(ignoreJar)) {
									continue target;
								}
							}
							FileUtil.copyFiles(file1.getAbsolutePath(), de, true, null);
						}
					}
				} else {
					copy(file, destDir);
				}
			}
		}
	}

}
